//*****************************************************************************
//
// uart_echo.c - Example for reading data from and writing data to the UART in
//               an interrupt driven fashion.
//
// Copyright (c) 2011 Texas Instruments Incorporated.  All rights reserved.
// Software License Agreement
// 
// Texas Instruments (TI) is supplying this software for use solely and
// exclusively on TI's microcontroller products. The software is owned by
// TI and/or its suppliers, and is protected under applicable copyright
// laws. You may not combine this software with "viral" open-source
// software in order to form a larger program.
// 
// THIS SOFTWARE IS PROVIDED "AS IS" AND WITH ALL FAULTS.
// NO WARRANTIES, WHETHER EXPRESS, IMPLIED OR STATUTORY, INCLUDING, BUT
// NOT LIMITED TO, IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
// A PARTICULAR PURPOSE APPLY TO THIS SOFTWARE. TI SHALL NOT, UNDER ANY
// CIRCUMSTANCES, BE LIABLE FOR SPECIAL, INCIDENTAL, OR CONSEQUENTIAL
// DAMAGES, FOR ANY REASON WHATSOEVER.
// 
// This is part of revision 8049 of the EK-LM4F232 Firmware Package.
//
//*****************************************************************************

#include "inc/hw_ints.h"
#include "inc/hw_memmap.h"
#include "inc/hw_types.h"
#include "driverlib/debug.h"
#include "driverlib/fpu.h"
#include "driverlib/gpio.h"
#include "driverlib/interrupt.h"
#include "driverlib/sysctl.h"
#include "driverlib/uart.h"
#include "driverlib/rom.h"
#include "utils/uartstdio.h"
#include "utils/crc.h"

#ifndef TRUE
	#define TRUE 1
#endif

#ifndef FALSE
	#define FALSE 0
#endif

#define buffer_size 40
unsigned char buffer[buffer_size];
unsigned int buffer_position = 0; 
 

struct packetHeader
{
	unsigned short OpCode;
	char PacketDataLength;
};
//*****************************************************************************
//
// LIFTI VerifyPacket function. Verify actual CRC with packet CRC
//
//*****************************************************************************
	int VerifyPacket(char* packet) {
		unsigned char PacketDataLength = packet[2];
		//sizeof (struct PacketHeader)
		unsigned int PacketLength = 3 + PacketDataLength; //Not including CRC
		unsigned short packetCRC = *((unsigned short *)(packet + PacketLength)); //Pull CRC16 from Packet
		unsigned short actualCRC = Crc16(0, (const unsigned char *)packet, PacketLength);	//Calculate CRC16 from recv'd data

		//Debug
		UARTprintf("PacketLength=%u ", PacketDataLength);
		UARTprintf("packetCRC=0x%x ", packetCRC);	  //doesnt display the full CRC value
		UARTprintf("actualCRC=0x%x ", actualCRC);

		if (actualCRC == packetCRC)
			return TRUE;
		else
			return FALSE;

	}
//*****************************************************************************
//
// LIFTI GetPacket function. Pulls Packet from Receive buffer into local buffer
//
//*****************************************************************************
	int GetPacket (char* local_buffer) {
		unsigned char PacketDataLength;
		unsigned char PacketLength;
		int i;

		//Check if receive buffer has enough chars in it
		// Need at least 2 byte opcode + 1 byte lenght + ?? bytes data + 2 bytes CRC
		PacketDataLength = buffer[2];
		PacketLength = PacketDataLength + 5;
		if (buffer_position < PacketLength)
			return FALSE;
		
		//Disable Receive Interrupts
		//fixme

		//Copy packet from receive buffer into local buffer
		for (i = 0; i < PacketLength; i++) 
		{
			local_buffer[i] = buffer[i];
		}
		//Update buffer length
		buffer_position -= (PacketLength);
		//Shift buffer PacketLength bytes to the left
		for (i = 0; i < buffer_position; i++) 
		{
			buffer[i] = buffer[i + (PacketLength)];
		}

		//Enable Receive Interrupts
		//fixme

		return TRUE;
	}

//*****************************************************************************
//
// The error routine that is called if the driver library encounters an error.
//
//*****************************************************************************
#ifdef DEBUG
	void __error__(char *pcFilename, unsigned long ulLine)
	{
	}
#endif

//*****************************************************************************
//
// The UART interrupt handler.
//
//*****************************************************************************
void UARTIntHandler(void)
{
    unsigned long ulStatus;
    //
    // Get the interrrupt status.
    //
    ulStatus = ROM_UARTIntStatus(UART0_BASE, true);
    //
    // Clear the asserted interrupts.
    //
    ROM_UARTIntClear(UART0_BASE, ulStatus);
    //
    // Loop while there are characters in the receive FIFO.
    //
    while(ROM_UARTCharsAvail(UART0_BASE) && buffer_position < buffer_size)
    {
    	buffer[buffer_position++] = ROM_UARTCharGetNonBlocking(UART0_BASE);
    }
}
//*****************************************************************************
//
// Send a string to the UART.
//
//*****************************************************************************
void
UARTSend(const unsigned char *pucBuffer, unsigned long ulCount)
{
    //
    // Loop while there are more characters to send.
    //
    while(ulCount--)
    {
        //
        // Write the next character to the UART.
        //
        ROM_UARTCharPutNonBlocking(UART0_BASE, *pucBuffer++);
    }
}
//*****************************************************************************
//
// This example demonstrates how to send a string of data to the UART.
//
//*****************************************************************************
int main(void)
{
char local_buf[20];
    //
    // The FPU should be enabled because some compilers will use floating-
    // point registers, even for non-floating-point code.  If the FPU is not
    // enabled this will cause a fault.  This also ensures that floating-
    // point operations could be added to this application and would work
    // correctly and use the hardware floating-point unit.  Finally, lazy
    // stacking is enabled for interrupt handlers.  This allows floating-
    // point instructions to be used within interrupt handlers, but at the
    // expense of extra stack usage.
    //
    FPUEnable();
    FPULazyStackingEnable();
    //
    // Set the clocking to run directly from the crystal.
    //
    ROM_SysCtlClockSet(SYSCTL_SYSDIV_1 | SYSCTL_USE_OSC | SYSCTL_OSC_MAIN | SYSCTL_XTAL_16MHZ);
    //
    // Enable the peripherals used by this example.
    //
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_GPIOA);
    ROM_SysCtlPeripheralEnable(SYSCTL_PERIPH_UART0);
    //
    // Enable processor interrupts.
    //
    ROM_IntMasterEnable();
    //
    // Set GPIO A0 and A1 as UART pins.
    //
    ROM_GPIOPinTypeUART(GPIO_PORTA_BASE, GPIO_PIN_0 | GPIO_PIN_1);
    //
    // Configure the UART for 115,200, 8-N-1 operation.
    //
    ROM_UARTConfigSetExpClk(UART0_BASE, ROM_SysCtlClockGet(), 115200, (UART_CONFIG_WLEN_8 | UART_CONFIG_STOP_ONE | UART_CONFIG_PAR_NONE));
    //
    // Enable the UART interrupt.
    //
    ROM_IntEnable(INT_UART0);
    ROM_UARTIntEnable(UART0_BASE, UART_INT_RX | UART_INT_RT);
    //
    // Initialize the UART.
    //
    //ROM_GPIOPinConfigure(GPIO_PA0_U0RX);
    //ROM_GPIOPinConfigure(GPIO_PA1_U0TX);
    UARTStdioInit(0);
    //
    // Loop forever echoing data through the UART.
    //
    while(1)
    {							    
		UARTprintf("%u : %s\n", buffer_position, buffer);
		UARTprintf("%u \n", GetPacket(local_buf));
    }
}
